<template>
  <div class="chart-content-wrapper" @mouseenter="mouseenter()" @mouseleave="mouseleave">
    <top-filter :title="reportName" ref="topFilter" :isShowHelp="true" :helpContent="remark">
      <double-check-filter :pageChange="pageChange" :isParentLinkChild="true" @confirmDoubleSelect="planAreaSelect" defaultText="统筹区"
                           :filter="filterN" type="planArea"></double-check-filter>
    </top-filter>
    <div class="chart-container" v-show="isShowChart">
      <div id="base-on-payment-level-analyse-id" class="chart-type1"></div>
      <Summarize :showSummarizeText="conclusion"></Summarize>
    </div>
  </div>
</template>

<script>
  import {setChartHeight, seqencingArr, loadingOpt} from '../../../assets/js/utils.js'
  import SingleListFilter from '../../last/filter/single-list-filter.vue'
  import DoubleCheckFilter from '../../last/filter/double-check-filter.vue'
  import TopFilter from '../../last/filter/top-filter1.vue'
  import {getBaseSalaryLevelAnalyse} from "../../../api/last-api";
  import Summarize from '../../last/summarize/summarize.vue'
  import SingleListFilterWithoutCb from '../../last/filter/single-list-filter-without-checkbox'
  export default {
    name: 'chart2',
    props: ['isChange', 'filter','pageChange'],
    components: {
      SingleListFilter,
      DoubleCheckFilter,
      TopFilter,
      Summarize,
      SingleListFilterWithoutCb
    },
    data () {
      return {
        filterN: JSON.parse(JSON.stringify(this.filter)),
        conclusion: '',
        remark: '',
        areaCode: null,
        hospLevel: this.filter.nc.hospitalRankType[1].selectId,
        queryYear: this.filter.years[0],
        json: {},
        reportName: '基于缴费工资的缴费水平分析',
        isShowChart: true,
        height: 400
      }
    },
    created(){

    },
    mounted(){
      let areaCode = []
      this.filter.nc.planArea.map((item, index) => {
        if (index > 0 && index <= 6) {
          areaCode.push(item.selectId)
        }
      })
      this.areaCode = areaCode.join(',');
      setChartHeight();
      this.initMyChart();
      //给echart 加loading效果
      this.myChart.showLoading(loadingOpt);
      this.getData();

    },
    watch: {
      pageChange(){
        let areaCode = []
        this.filter.nc.planArea.map((item, index) => {
          if (index > 0 && index <= 6) {
            areaCode.push(item.selectId)
          }
        })
        this.areaCode = areaCode.join(',');
        this.initMyChart();
        this.getData();
      },
      isChange(){
        setTimeout(() => {
          setChartHeight();
          setTimeout(() => {
            this.myChart.resize();
          }, 10)
        }, 101)
      }
    },
    methods: {
      initMyChart() {
        // 基于准备好的dom，初始化echarts实例
        this.myChart = this.$echarts.init(document.getElementById('base-on-payment-level-analyse-id'), null, {renderer: 'canvas'})
        let that = this;
        this.myChart.off('legendselectchanged');
        this.myChart.on('legendselectchanged', function (params) {
          let option = this.getOption();
          let select_key = Object.keys(params.selected);
          if (!params.selected[params.name]) {
            select_key.map(res => {
              option.legend[0].selected[res] = true;
            });
          } else {
            select_key.map(res => {
              option.legend[0].selected[res] = true;
            });
            option.legend[0].selected[params.name] = true;
          }
          let legend = []
          that.myChart.dispatchAction({
            type: 'legendselectchanged',
            batch: legend
          });
          that.myChart.setOption(option)
        })
      },
      mouseenter(){
        this.$refs.topFilter._hideChartTitle()
      },
      mouseleave() {
        this.$refs.topFilter._showChartTitle()
      },
      getData(){
        setChartHeight();

        getBaseSalaryLevelAnalyse(this.areaCode).then(response => {
          let json = response.data;
          if (response.code === 0) {
            this.isShowChart = true;
            this.myChart.hideLoading();
            this.reportName = json.reportName;
            this.conclusion = json.conclusion;
            this.remark = json.remark;
            this.drawLine(json)
          } else {
            this.isShowChart = false;
          }
        }).catch(res => {
//          console.log(res)
          this.isShowChart = false;
        })
      },
      avg(arry){
        let sum = 0;
        let len = arry.length;
        for (let i = 0; i < len; i++) {
          sum += arry[i];
        }
        let d = parseInt((sum / len) * 100) / 100;
        return d;
      },
      chooseYear(year){
        this.queryYear = year;
        this.myChart.clear();
        this.myChart.showLoading(loadingOpt)
        this.getData();
        //选择年份后执行事件
      },
      planAreaSelect(filter){
        //统筹区选择
        this.areaCode = filter.join(',')
        this.myChart.clear();
        this.myChart.showLoading(loadingOpt)
        this.getData();
      },
      hospLevelSelect(filter){
        //医院级别选择
        this.hospLevel = filter.join(',');
        this.myChart.clear();
        this.myChart.showLoading(loadingOpt)
        this.getData();
      },
      drawLine(json){
//        let avg = this.avg(json.institutionGrowthRateList)
//        let curYear = `${this.queryYear}年`;
//        let lastYear = `${this.queryYear - 1}年`;
//        let hosName = [];
//        json.medInstitutionList.map((item, index) => {
//          let length = item.length;
//          if (length > 7) {
//            item = item.substring(0, 7) + '...'
//          }
//          hosName.push(item);
//        })
//        let max = null
//        let min = null
//        let num = seqencingArr(json.institutionGrowthRateList, json.avgGrowthRate);
//        if (json.avgGrowthRate > 0 && num) {
//          max = num
//        } else if (json.avgGrowthRate < 0 && num) {
//          min = -num
//        }
        // 绘制图表
//        let divDotIndex = 4; // 分段显示visualMap中对应的分割点
//        let maxDotIndex = json.avgAddRateList.length - 1;
        let divDotIndex = 5; // 分段显示visualMap中对应的分割点
        let maxDotIndex = 8;

        let minBoxPlotList = [];
        let showBoxPlotList = JSON.parse(JSON.stringify(json.boxPlotList))
        showBoxPlotList.forEach((item) => {
          minBoxPlotList.push(item[0] + '');
          let iqr = item[3] - item[1]
          let viMin = item[1] - 1.5 * iqr;
          let viMax = item[3] + 1.5 * iqr;
          if (viMin > item[0]) {
            item[0] = viMin
          }
          if (viMax < item[4]) {
            item[4] = viMax
          }
        })

        console.log(JSON.stringify(minBoxPlotList))

        this.myChart.setOption({
          // Make gradient line here
          title: {
            show: false,
            subtext: '单位：万元',
            left: '4%',
            top: '4%',
            x: 'left',
            subtextStyle: {
              color: '#fff'
            }
          },
          grid: [//此参数可在一个dom中划分多个图表 可设置不同图表的位置
            {
              width: '18%',
              left: '75%',
              height: '78%',
              top: '12%',
//              tooltip: {
//                formatter: "{b}</br>{c}%" //给当前坐标系添加弹窗
//              }
            },
            {
              width: '45%',
              left: '15%',
              height: '78%',
              top: '12%',
              tooltip: {
                show: true,
                trigger: 'axis',
                axisPointer: {
                  type: 'shadow'
                },
              }
            }
          ],
          legend: {
            left: '20%',
            top: '95%',
            icon: 'circle',
            itemWidth: 8,
            itemHeight: 10,
            itemGap: 20,
            data: ['最小值', '众数', '平均数'],
            textStyle: {
              color: '#fff'
            },
//            tooltip: {
//              show: true,
//
//              formatter: function (params) {
//                let txt = '';
//                // if(params.name=='增长额(正)'){
//                //   txt = '增长额（正）</br>即区域内医疗机构医疗总收入增长额=（区</br>域内医疗机构本年度住院收入+本年度门</br>诊收入）-（区域内医疗机构上年年度院收</br>入+上年度门诊收入）'
//                // }else if(params.name=='增长额(负)'){
//                //   txt = '增长额（负）</br>即区域内医疗机构医疗总收入增长额=（区</br>域内医疗机构本年度住院收入+本年度门</br>诊收入）-（区域内医疗机构上年年度院收</br>入+上年度门诊收入）'
//                // }else{
//                //   txt = '总额'
//                // }
//                return params.name + '医疗费用总额';
//              }
//            }
          },
          tooltip: {
            show: true,
            textStyle: {
              fontSize: 12
            },
            formatter: function (params) {
              let dataIndex = params[0].dataIndex;
//              console.log(JSON.stringify(json))
//              console.log(params)
              return `<span style="color: #fff">缴费工资</span></br>
                      <span style="color: #fff">年份: ${json.yearList[dataIndex]}</span></br>
                      <span style="color: #fff">最小值: ${json.boxPlotList[dataIndex][0]}元</span></br>
                      <span style="color: #fff">平均值: ${json.avgList[dataIndex][0]}元</span></br>
                      <span style="color: #fff">中位数: ${json.boxPlotList[dataIndex][2]}元</span></br>
                      <span style="color: #fff">众数: ${json.modeList[dataIndex][0]}元</span></br>
                      <span style="color: #fff">最大值: ${json.boxPlotList[dataIndex][4]}元</span></br>`;
            }
          },
          xAxis: [
            {
              type: 'value',
              /* show:true,*/
              splitLine: {
                show: false
              },
              position: 'top',
              /* minInterval:5,*/
//              max: max,
//              min: min,
              splitNumber: 2,
              axisLine: {
                show: false
              },
              axisLabel: {
                formatter: '{value}',
                textStyle: {
                  color: '#fff'
                }
              },
              axisTick: {
                show: false
              }

            },
            {
              type: 'value',
              name: '单位：元',
              nameTextStyle: {
                color: '#ffffff'
              },
              splitLine: {
                show: true,
                lineStyle: {
                  color: '#2a4565',
                  type: 'dashed'
                }
              },
              gridIndex: 1,
              splitNumber: 3,
              axisLine: { //y轴的横线是否显示
                show: true,
                lineStyle: {
                  color: '#2A4565',
                  type: 'solid'
                }
              },
              axisLabel: {
                show: true,
                formatter: function (item) {
                  if (item == 0) {
                    return ''
                  } else {
//                    return item.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,')
                    return item.toString().replace(/(\d)(?=(\d{3}))/g, '$1,')
                  }
                },
                textStyle: {
                  color: '#fff'
                }
              },
              axisTick: {
                show: false
              }
            }
          ],
          yAxis: [
            {
              /*data: json.medInstitutionList,*/
              data: json.yearList,
              splitLine: {
                show: false
              },
              axisLine: {
                show: true,//显示y轴坐标线并设置为虚线
                lineStyle: {
                  type: 'solid',
                  color: '#2a4565'
                }
              },
              axisTick: {
                show: false //不显示y轴坐标的刻度
              },
              axisLabel: {
                show: false //不显示y轴坐标数值
              }
            },
            {
              /*data: json.medInstitutionList,*/
//              name: '单位：元',
              nameTextStyle: {
                color: '#ffffff'
              },
              data: json.yearList,
              gridIndex: 1,
              axisLine: { //y轴的横线是否显示
                show: true,
                lineStyle: {
                  color: '#2A4565',
                  type: 'solid'
                }
              },
              axisTick: { //y轴的刻度短竖线是否显示
                show: false
              },
              axisLabel: {
                formatter: '{value}',
                textStyle: {
                  color: '#fff'
                },
              },
            }
          ],
          visualMap: [
            {
              show: true,
              dimension: 1,
              seriesIndex: 0,
              left: '56%',
              top: '95%',
              orient: "horizontal",
              itemWidth: 10,
              itemHeight: 10,
              textStyle: {
                color: '#fff'
              },
              pieces: [
                {
                  gt: divDotIndex,
                  lte: maxDotIndex,
//                  color: '#67ffdb',
                  color: 'transparent',
                  symbol: 'circle',
                  label: '  ',
                },
                {
                  lte: divDotIndex,
                  color: '#2b9ff6',
                  symbol: 'circle',
                  label: '平均值增长率'
                }
              ],
            }
          ],
          series: [
            {
              type: 'line',
              showSymbol: true,
              data: json.avgAddRateList,
              symbolSize: 10,
              tooltip: {
                show: true,
                formatter: function (params) {
                  let dataIndex = params.dataIndex;
//              console.log(JSON.stringify(json))
//                  console.log(params)
                  if (dataIndex > divDotIndex) {
                    return `<span style="color: #fff">平均值增长率（同比）</span></br>
                      <span style="color: #fff">年份: ${json.yearList[dataIndex]}</span></br>
                      <span style="color: #fff">增长率: ${json.avgAddRateList[dataIndex]}%</span></br>`;
                  } else {
                    return `<span style="color: #fff">平均值增长率</span></br>
                      <span style="color: #fff">年份: ${json.yearList[dataIndex]}</span></br>
                      <span style="color: #fff">增长率: ${json.avgAddRateList[dataIndex]}%</span></br>`;
                  }
                }
              },
              label: {
                show: true,
                position: 'right',
                formatter: '{c}%',
                color: '#fff'
              },
//              markLine: {
//                label: {
//                  position: 'start',
//                  /*formatter: '平均增长\n率{c}%',*/
//                  formatter: '{c}%',
//                  color: '#fff',
//                },
//                symbol: 'none',//设置平均线的没样式
//                data: [
//                  {
//                    type: 'average',
//                    name: '平均增长率',
//                    tooltip: {
//                      show: true,
//                      formatter(params){
//                        return `<span style="color:${params.color}">平均增长率</span></br><span style='color:#c7c7c7'>${params.value}%</span>`
//                      }
//                    }
//                  }
//                ],
//                lineStyle: {
//                  color: '#ff6a93'
//                }
//              }
            },
            {
              name: 'boxplot',
              type: 'boxplot',
              data: showBoxPlotList,
              xAxisIndex: 1,
              yAxisIndex: 1,
              itemStyle: {
                color: 'rgba(12,12,12,0)',
                borderColor: '#E16288',
              }
            },
            {
              type: 'scatter',
              name: '最小值',
              showSymbol: true,
              data: minBoxPlotList,
              xAxisIndex: 1,
              yAxisIndex: 1,
              symbolSize: 10,
              label: {
                show: false,
                position: 'right',
                formatter: '{c}%',
                color: '#fff'
              },
              itemStyle: {
                color: '#BB61E3'
              },
//              tooltip: {
//                show:true,
//                formatter:function(par){
//                  let i = par.dataIndex;
//                  let txt = '';
//                  json.medInstitutionList.map((item,index)=>{
//                    if(index==i){
//                      txt = `<span style="color:${par.color}">${item}</span><br><span style="color:#c7c7c7">增长率：${par.value}%</span>`
//                    }
//                  })
//                  return txt;
//                }
//              },
//              markLine:{
//                label:{
//                  position: 'start',
//                  formatter: '{c}%',
//                  color:'#fff'
//                },
//                symbol:'none',
//                data : [
//                  {
//                    xAxis:json.avgGrowthRate,
//                    name: '平均增长率',
//                    tooltip: {
//                      show:true,
//                      formatter: function(par){
//                        return `<span style="color:${par.color}">平均增长率</span><br><span style="color:#c7c7c7">${par.value}%</span>`
//                      }
//                    }
//                  }
//                ],
//                lineStyle: {
//                  color:'#ff6a93'
//                }
//              }
            },
            {
              type: 'scatter',
              name: '众数',
              showSymbol: true,
              data: json.modeList,
              xAxisIndex: 1,
              yAxisIndex: 1,
              symbolSize: 10,
              label: {
                show: false,
                position: 'right',
                formatter: '{c}%',
                color: '#fff'
              },
              itemStyle: {
                color: '#FFD66A'
              },
//              tooltip: {
//                show:true,
//                formatter:function(par){
//                  let i = par.dataIndex;
//                  let txt = '';
//                  json.medInstitutionList.map((item,index)=>{
//                    if(index==i){
//                      txt = `<span style="color:${par.color}">${item}</span><br><span style="color:#c7c7c7">增长率：${par.value}%</span>`
//                    }
//                  })
//                  return txt;
//                }
//              },
//              markLine:{
//                label:{
//                  position: 'start',
//                  formatter: '{c}%',
//                  color:'#fff'
//                },
//                symbol:'none',
//                data : [
//                  {
//                    xAxis:json.avgGrowthRate,
//                    name: '平均增长率',
//                    tooltip: {
//                      show:true,
//                      formatter: function(par){
//                        return `<span style="color:${par.color}">平均增长率</span><br><span style="color:#c7c7c7">${par.value}%</span>`
//                      }
//                    }
//                  }
//                ],
//                lineStyle: {
//                  color:'#ff6a93'
//                }
//              }
            },
            {
              type: 'scatter',
              name: '平均数',
              showSymbol: true,
              data: json.avgList,
              xAxisIndex: 1,
              yAxisIndex: 1,
              symbolSize: 10,
              label: {
                show: false,
                position: 'right',
                formatter: '{c}%',
                color: '#fff'
              },
              itemStyle: {
                color: '#67FFDB'
              },
//              tooltip: {
//                show:true,
//                formatter:function(par){
//                  let i = par.dataIndex;
//                  let txt = '';
//                  json.medInstitutionList.map((item,index)=>{
//                    if(index==i){
//                      txt = `<span style="color:${par.color}">${item}</span><br><span style="color:#c7c7c7">增长率：${par.value}%</span>`
//                    }
//                  })
//                  return txt;
//                }
//              },
//              markLine:{
//                label:{
//                  position: 'start',
//                  formatter: '{c}%',
//                  color:'#fff'
//                },
//                symbol:'none',
//                data : [
//                  {
//                    xAxis:json.avgGrowthRate,
//                    name: '平均增长率',
//                    tooltip: {
//                      show:true,
//                      formatter: function(par){
//                        return `<span style="color:${par.color}">平均增长率</span><br><span style="color:#c7c7c7">${par.value}%</span>`
//                      }
//                    }
//                  }
//                ],
//                lineStyle: {
//                  color:'#ff6a93'
//                }
//              }
            }
          ]
        });
      }
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>
